import 'package:check_app/dao/spec_dao.dart';
import 'package:check_app/dao/subject_dao.dart';
import 'package:check_app/dao/tempInput_dao.dart';
import 'package:check_app/page/SelectPage.dart';
import 'package:check_app/util/pref_util.dart';
import 'package:check_app/util/uploadImage_util.dart';
import 'package:check_app/widgets/Picture.dart';
import 'package:check_app/widgets/RadioSelect.dart';
import 'package:check_app/widgets/deleteModal.dart';
import 'package:check_app/widgets/downModal.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class TempInputPage extends StatefulWidget {
  final int taskId;
  final int id;
  final String code;
  const TempInputPage({Key key, this.taskId, this.id, this.code})
      : super(key: key);
  @override
  State<StatefulWidget> createState() => new _TempInputPageState();
}

class _TempInputPageState extends State<TempInputPage> {
  bool _loading = false;
  String barcode = '';
  TextEditingController _name = new TextEditingController();
  TextEditingController _code = new TextEditingController();
  GlobalKey _formKey = new GlobalKey<FormState>();

  List<Map> jianyanList;
  List specList = [];
  List<String> picUrlList = [];
  String subjectId;
  String subName;
  String verdictType;
  Map<String, TextEditingController> _controllers = Map();
  Map<String, String> _radioValue = Map();

  @override
  void initState() {
    super.initState();
    jianyanList = [
      {
        'lable': '合格',
        'value': 'PASS',
      },
      {
        'lable': '不合格',
        'value': 'FAIL',
      },
    ];
    if (widget.id != null) {
      getData();
    } else {
      verdictType = jianyanList[0]['value'];
    }
  }

  Future<Null> getData() async {
    setState(() {
      _loading = true;
    });
    try {
      var result = await SubjectDao.fetchSubjectInfo(
          '/subject/' + widget.id.toString(), {
        'id': widget.id.toString(),
      });
      setState(() {
        _loading = false;
      });
      if (result.success) {
        setState(() {
          subjectId = result.data.subId.toString();
          subName = result.data.subName;
          _name.text = result.data.subName;
          _code.text = result.data.code;
          verdictType = result.data.verdictType;
          specList = result.data.specList;
          picUrlList = result.data.picUrlList ?? [];
        });
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  Future<Null> getSpecList() async {
    setState(() {
      _loading = true;
    });
    try {
      var result = await SpectDao.fetch(
          '/subjectClass/' + subjectId.toString() + '/spec/list', {
        'subjectClassId': subjectId,
      });
      setState(() {
        _loading = false;
      });
      if (result.success) {
        setState(() {
          specList = result.data;
        });
        Fluttertoast.showToast(
          msg: result.message,
        );
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  Future<Null> saveInput() async {
    setState(() {
      _loading = true;
    });
    try {
      var result = await TempInputDao.save({
        'taskId': widget.taskId,
        'id': widget.id,
        'subId': subjectId,
        'code': _code.text,
        'verdictType': verdictType ?? jianyanList[0]['value'],
        'specList': handleData(),
        'picUrlList': picUrlList,
      });
      setState(() {
        _loading = false;
      });
      if (result.success) {
        Navigator.of(context).pop();
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  handleData() {
    return specList
        .map((item) => {
              "id": item.id,
              "key": item.key,
              "name": item.name,
              "options": item.options,
              "type": item.type,
              "value": getValue(item),
            })
        .toList();
  }

  getValue(item) {
    if (item.type == 'INPUT_DECIMAL') {
      return _controllers[item.key].text;
    } else {
      return _radioValue[item.key];
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color.fromRGBO(248, 248, 249, 1),
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          centerTitle: true,
          title: Text(widget.code ?? '数据录入'),
        ),
        body: SafeArea(
          child: ModalProgressHUD(
            inAsyncCall: _loading,
            child: Stack(
              children: <Widget>[
                SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(top: 16),
                        decoration: BoxDecoration(
                          border: Border(
                            top: BorderSide(
                              width: 0.5,
                              color: Color.fromRGBO(229, 229, 229, 1),
                            ),
                          ),
                        ),
                        child: Form(
                          key: _formKey,
                          autovalidate: false,
                          child: Column(
                            children: <Widget>[
                              // 第一部分
                              // 待检物名称
                              Container(
                                height: 62,
                                width: double.infinity,
                                padding: EdgeInsets.only(right: 16),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  border: Border(
                                    bottom: BorderSide(
                                      width: 0.5,
                                      color: Color.fromRGBO(229, 229, 229, 1),
                                    ),
                                  ),
                                ),
                                child: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () async {
                                    if (subName != null && subName != '')
                                      return null;
                                    var result = await Navigator.of(context)
                                        .push(MaterialPageRoute(builder: (_) {
                                      return SelectPage(
                                        type: 'subject',
                                        title: '待检物',
                                        placeholder: '请输入待检物名称',
                                        label: '当前待检物',
                                        value: _name.text,
                                      );
                                    }));
                                    setState(() {
                                      _name.text = result.name;
                                      subjectId = result.id.toString();
                                    });
                                    getSpecList();
                                  },
                                  child: Row(
                                    children: <Widget>[
                                      Container(
                                        width: 120,
                                        padding: EdgeInsets.only(left: 16),
                                        child: Text(
                                          '待检物名称',
                                          style: TextStyle(
                                            fontSize: 16,
                                            height: 19 / 16,
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: TextFormField(
                                          enabled: false,
                                          controller: _name,
                                          style: TextStyle(
                                            fontSize: 15.5,
                                            height: 22.5 / 15.5,
                                            color:
                                                Color.fromRGBO(43, 44, 46, 1),
                                          ),
                                          decoration: InputDecoration(
                                            fillColor: Colors.pink,
                                            contentPadding: EdgeInsets.fromLTRB(
                                                0, 0, 16, 0),
                                            hintText: "请选择待检物",
                                            hintStyle: TextStyle(
                                              fontSize: 15.5,
                                              height: 22.5 / 15.5,
                                              color: Color.fromRGBO(
                                                  181, 184, 189, 1),
                                            ),
                                            border: OutlineInputBorder(
                                              borderSide: BorderSide.none,
                                            ),
                                          ),
                                          validator: (v) {
                                            return v.trim().length > 0
                                                ? null
                                                : '待检物不能为空';
                                          },
                                        ),
                                      ),
                                      Image(
                                        image: AssetImage(
                                            'assets/images/chevron_gray.png'),
                                        width: 8,
                                        height: 13,
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              // 待检物编码
                              Container(
                                height: 62,
                                width: double.infinity,
                                padding: EdgeInsets.only(right: 16),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  border: Border(
                                    bottom: BorderSide(
                                      width: 0.5,
                                      color: Color.fromRGBO(229, 229, 229, 1),
                                    ),
                                  ),
                                ),
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      width: 120,
                                      padding: EdgeInsets.only(left: 16),
                                      child: Text(
                                        '待检物编码',
                                        style: TextStyle(
                                          fontSize: 16,
                                          height: 19 / 16,
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: TextFormField(
                                        enabled: true,
                                        controller: _code,
                                        style: TextStyle(
                                          fontSize: 15.5,
                                          height: 22.5 / 15.5,
                                          color: Color.fromRGBO(43, 44, 46, 1),
                                        ),
                                        decoration: InputDecoration(
                                          fillColor: Colors.pink,
                                          contentPadding:
                                              EdgeInsets.fromLTRB(0, 0, 16, 0),
                                          hintText: "请扫描或输入待检物编码",
                                          hintStyle: TextStyle(
                                            fontSize: 15.5,
                                            height: 22.5 / 15.5,
                                            color: Color.fromRGBO(
                                                181, 184, 189, 1),
                                          ),
                                          border: OutlineInputBorder(
                                            borderSide: BorderSide.none,
                                          ),
                                        ),
                                        keyboardType: TextInputType.phone,
                                        textInputAction: TextInputAction.done,
                                        validator: (v) {
                                          return v.trim().length > 0
                                              ? null
                                              : '待检物编码不能为空';
                                        },
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        qrscan();
                                      },
                                      child: Image(
                                        image: AssetImage(
                                            'assets/images/scan.png'),
                                        width: 16,
                                        height: 16,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              // 第二部分
                              Container(
                                child: Column(
                                  children: getList(specList),
                                ),
                              ),
                              verdictType != null
                                  ? RadioSelect(
                                      title: '检验结论',
                                      defaultvalue: verdictType,
                                      items: jianyanList,
                                      callback: (value) {
                                        verdictType = value['value'];
                                      },
                                    )
                                  : SizedBox(),
                              // 第三部分
                              Container(
                                alignment: Alignment.centerLeft,
                                margin: EdgeInsets.fromLTRB(16, 12, 16, 8),
                                child: Text(
                                  '图片（选填）',
                                  style: TextStyle(
                                    fontSize: 14,
                                    height: 20 / 14,
                                    color: Color.fromRGBO(150, 151, 154, 1),
                                  ),
                                ),
                              ),
                              // 图片
                              Container(
                                padding: EdgeInsets.all(16),
                                decoration: BoxDecoration(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  border: Border(
                                    top: BorderSide(
                                      width: 0.5,
                                      color: Color.fromRGBO(229, 229, 229, 1),
                                    ),
                                    bottom: BorderSide(
                                      width: 0.5,
                                      color: Color.fromRGBO(229, 229, 229, 1),
                                    ),
                                  ),
                                ),
                                child: Picture(
                                  count: 4,
                                  picList: picUrlList,
                                  onAdd: () {
                                    showModalBottomSheet(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return DownModal(
                                          cameraCb: () async {
                                            final url = await UploadImageUtil()
                                                .getImageFromCamera();
                                            setState(() {
                                              picUrlList.add(url);
                                              _loading = false;
                                            });
                                          },
                                          photoCb: () async {
                                            final urlList =
                                                await UploadImageUtil()
                                                    .loadAssets(
                                                        9 - picUrlList.length);
                                            setState(() {
                                              for (var value in urlList) {
                                                picUrlList
                                                    .add(value.toString());
                                              }
                                              _loading = false;
                                            });
                                          },
                                        );
                                      },
                                    );
                                  },
                                  onRemove: (url) {
                                    showModalBottomSheet(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return DeleteModal(
                                          onRemove: () {
                                            setState(() {
                                              picUrlList.remove(url);
                                            });
                                          },
                                        );
                                      },
                                    );
                                  },
                                ),
                              ),
                              Container(
                                padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
                                width: double.infinity,
                                child: MaterialButton(
                                  onPressed: () async {
                                    if ((_formKey.currentState as FormState)
                                        .validate()) {
                                      final result = await PrefUtil()
                                          .openAlertDialog(context, '是否保存数据');
                                      if (result == 'ok') {
                                        saveInput();
                                      }
                                    }
                                  },
                                  color: Colors.blue,
                                  textColor: Colors.white,
                                  height: 44,
                                  child: Text(
                                    '提交',
                                    style: TextStyle(
                                      fontSize: 14,
                                      height: 24 / 17,
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                // Positioned(
                //   left: 0,
                //   right: 0,
                //   bottom: 20,
                //   child: Container(
                //     padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
                //     width: double.infinity,
                //     child: MaterialButton(
                //       onPressed: () {
                //         if ((_formKey.currentState as FormState).validate()) {
                //           saveInput();
                //         }
                //       },
                //       color: Colors.blue,
                //       textColor: Colors.white,
                //       height: 44,
                //       child: Text(
                //         '提交',
                //         style: TextStyle(
                //           fontSize: 14,
                //           height: 24 / 17,
                //         ),
                //       ),
                //     ),
                //   ),
                // ),
              ],
            ),
          ),
        ));
  }

  // 获取菜单项widget列表
  List<Widget> getList(List list) {
    return list.map<Widget>((item) => createItem(item)).toList();
  }

  // 生成���个菜单项
  Widget createItem(item) {
    if (item.type == 'INPUT_DECIMAL') {
      if (_controllers[item.key] == null) {
        _controllers[item.key] = TextEditingController(text: item.value ?? '');
      }
      return Container(
        height: 62,
        width: double.infinity,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Color.fromRGBO(255, 255, 255, 1),
          border: Border(
            bottom: BorderSide(
              width: 0.5,
              color: Color.fromRGBO(229, 229, 229, 1),
            ),
          ),
        ),
        child: Row(
          children: <Widget>[
            Container(
              width: 120,
              padding: EdgeInsets.only(left: 16),
              child: Text(
                item.name,
                style: TextStyle(
                  fontSize: 16,
                  height: 19 / 16,
                ),
              ),
            ),
            Expanded(
              child: TextFormField(
                autofocus: false,
                controller: _controllers[item.key],
                onChanged: (text) {},
                style: TextStyle(
                  fontSize: 15.5,
                  height: 22.5 / 15.5,
                  color: Color.fromRGBO(43, 44, 46, 1),
                ),
                decoration: InputDecoration(
                  fillColor: Colors.pink,
                  contentPadding: EdgeInsets.fromLTRB(0, 0, 16, 0),
                  hintText: '请输入' + item.name,
                  hintStyle: TextStyle(
                    fontSize: 15.5,
                    height: 22.5 / 15.5,
                    color: Color.fromRGBO(181, 184, 189, 1),
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                  ),
                ),
                inputFormatters: [
                  WhitelistingTextInputFormatter(RegExp("[0-9.]"))
                ],
                keyboardType: TextInputType.number,
                validator: (v) {
                  return v.trim().length > 0 ? null : (item.name + '不能为空');
                },
              ),
            ),
          ],
        ),
      );
    } else {
      _radioValue[item.key] =
          item.value ?? strTolist(item.options, item.key)[0]['value'];
      return RadioSelect(
        title: item.name,
        defaultvalue:
            item.value ?? strTolist(item.options, item.key)[0]['value'],
        items: strTolist(item.options, item.key),
        callback: (value) {
          _radioValue[value['key']] = value['value'];
        },
      );
    }
  }

  strTolist(String str, String key) {
    var list = str.split(',');
    return list
        .map((item) => {'lable': item, 'value': item, 'key': key})
        .toList();
  }

  Future qrscan() async {
    try {
      String barcode = await scanner.scan();
      setState(() {
        _code.text = barcode;
      });
    } on FormatException {
      // NativeToast.show('已退出扫码');
    } catch (e) {
      // NativeToast.show('未知错误: $e');
    }
  }
}
